package client;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import javax.net.ssl.SSLSocket;

public class ClientListener extends Thread {
	protected SSLSocket socket;
	protected Client parent;
	protected BufferedWriter bw;
	protected BufferedReader br;
	protected boolean close;
	
	public ClientListener(Client p, SSLSocket s) {
		socket = s;
		parent = p;
		try {
			bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
			br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.println("failed to get streams");
		}
	} 
	
	public void run() {
		while(!close) {
			try {
				String msg = br.readLine();
				synchronized(parent.getLock()) {
					System.out.println(msg);
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				System.out.println("stream error");
				break;
			}
		}
		parent.removeListener(this);
	}
	
	public boolean sendMsg(String msg) {
		try {
			bw.write(msg);
			bw.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.println("message sending failed");
			return false;
		}
		return true;
	}
}
